package com.lw.leetcode.stack;

import java.util.Stack;

/**
 * 1209. 删除字符串中的所有相邻重复项 II
 *
 * @Author liw
 * @Date 2021/5/17 15:04
 * @Version 1.0
 */
public class RemoveDuplicates {
    public static void main(String[] args) {
        RemoveDuplicates test = new RemoveDuplicates();
        String pbbcggttciiippooaais = test.removeDuplicates("pbbcggttciiippooaais", 2);
        System.out.println(pbbcggttciiippooaais);
    }

    public String removeDuplicates(String s, int k) {

        Stack<Character> stack = new Stack<>();
        stack.add('0');
        Stack<Integer> count = new Stack<>();
        int length = s.length();

        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == stack.peek()) {
                int n = count.pop();
                if (k == ++n) {
                    stack.pop();
                } else {
                    count.add(n);
                }
            } else {
                count.add(1);
                stack.add(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!count.isEmpty()) {
            Integer n = count.pop();
            Character value = stack.pop();
            for (Integer j = 0; j < n; j++) {
                sb.append(value);
            }
        }
        return sb.reverse().toString();
    }

}
